import Vue from 'vue'
import Component from './func-videobox'

const VideoBoxConstructor = Vue.extend(Component)
const instances = []

const handleSeed = () => {
  let seed = sessionStorage.getItem("seed")
  if (!seed) {
    seed = 1000
  } else {
    seed = Number.parseInt(seed) + 1
  }
  sessionStorage.setItem("seed", seed)
  return seed
}
// 删除instances中记录
const removeInstance = (instance) => {
  if (!instance) return
  const len = instances.length
  const index = instances.findIndex(ist => ist.id === instance.id)
  instances.splice(index, 1)
}
const videoBox = (options) => {
  const { ...props } = options
  const instance = new VideoBoxConstructor({
    propsData: {
      ...props
    },
    data () {
      return {
      }
    }
  })
  const id = `video_box_${instance.videoDetail.id}`
  // 如果已经有则不新添加
  let isDuplicate = false
  instances.forEach(item => {
    if(item.id == id) {
      item.zindex = handleSeed()
      isDuplicate = true
    }
  })
  if(isDuplicate) {
    return
  }
  instance.id = id
  instance.vm = instance.$mount()
  let container = document.getElementById('app')
  container.appendChild(instance.vm.$el)
  instance.isVisible = true
  let zindex = handleSeed()
  instance.zindex = zindex
  instances.push(instance)
  instance.vm.$on('close', () => {
    instance.isVisible = false
  })
  instance.vm.$on('closed', () => {
    removeInstance(instance)
    // let container = document.getElementById('containerMain')
    container.removeChild(instance.$el)
    instance.vm.$destroy()
  })
  return instance.vm
}

export default videoBox
